package com.xiguthings.xiniu.iot.post.poster;

import java.io.IOException;
import java.util.Map;

import org.slf4j.Logger;

import com.xiguthings.xiniu.iot.common.PostData;
import com.xiguthings.xiniu.iot.post.common.HttpUtils;
import com.xiguthings.xiniu.iot.post.common.entity.PostResult;

public class SendPostRunable implements Runnable {
	private final static Logger LOGGER = org.slf4j.LoggerFactory.getLogger(SendPostRunable.class);

	private final PostData postData;
	private final PostCenter postCenter;

	public SendPostRunable(final PostData postData, final PostCenter postCenter) {
		super();
		this.postData = postData;
		this.postCenter = postCenter;
	}

	@Override
	public void run() {
	
		Map<String, Object> resMap = null;
		IOException exception = null;
		try {
			// 发送post请求，取得发送结果
			int tryCount = postData.getCount();

			resMap = HttpUtils.post(postData.getUrl(), postData.getData().toString().getBytes(), false);
			

			postData.setCount(tryCount + 1);// 增加发送的次数
		} catch (IOException e) {
			exception = e;
			LOGGER.error("post异常:{}", e);
		}
		// LOGGER.info("post结果:{} , {}", resMap);

		// 发送成功了
		if (resMap.get(HttpUtils.RESPONSE_CODE).equals(200)) {
			PostResult postResult = new PostResult(resMap, postData.getCount(), "ok", null);
			postCenter.postResult(postResult);

			return;
		}
		// 發送失敗了
		if (!resMap.get(HttpUtils.RESPONSE_CODE).equals(200)) {
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
			}
			if (postData.getCount() >= 2) {
				// 重试多次后失败,不再繼續發送
				PostResult postResult = new PostResult(resMap, postData.getCount(), null, exception);
				postCenter.postResult(postResult);
			
				return;
			}
			// 再次发送
			postData.setCount(postData.getCount());
			postCenter.tryPostAgain(postData);
			return;
		}
	}

}
